package com.serviceprovider.business.module.sp.transaction.services.dao.impl;

//~--- non-JDK imports --------------------------------------------------------

import com.serviceprovider.business.module.common.Page;
import com.serviceprovider.business.module.common.PaginationHelper;
import com.serviceprovider.business.module.sp.transaction.model.Batch;
import com.serviceprovider.business.module.sp.transaction.services.dao.interfaces.IBatchDao;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;

//~--- JDK imports ------------------------------------------------------------

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository("batchDaoImpl")
public class BatchDaoImpl extends SimpleJdbcDaoSupport implements IBatchDao {
    protected final Log      logger      = LogFactory.getLog(getClass());
    private BatchMapper      batchMapper = new BatchMapper();
    @Autowired
    @Qualifier("batchTransJdbcInsert")
    private SimpleJdbcInsert jdbcInsert;

    @Autowired
    public BatchDaoImpl(@Qualifier("jdbcTemplate") JdbcTemplate jdbcTemplate) {
        setJdbcTemplate(jdbcTemplate);
    }

    @Override
    public Batch findBatchByTransaction(int transactionId) {
        String sql = "SELECT distinct(b.batch_id),b.custom_label_1_name,b.custom_label_2_name,b.batch_date,b.order_id "
                     + "FROM batch b,transaction_details t " + "WHERE b.batch_id=t.batch_id and t.transaction_id="
                     + transactionId;

        return (Batch) getJdbcTemplate().queryForObject(sql, batchMapper);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Batch> findBatchByOrder(int orderId) {
        String sql = "SELECT * FROM batch WHERE order_id=" + orderId;

        return getJdbcTemplate().query(sql, batchMapper);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Batch> findBatchByPayee(int userId) {
        String sql = "SELECT distinct(b.batch_id),b.custom_label_1_name,b.custom_label_2_name,b.batch_date,b.order_id "
                     + "FROM batch b,transaction_user_amount t " + "WHERE b.batch_id=t.batch_id and t.user_id="
                     + userId;

        return getJdbcTemplate().query(sql, batchMapper);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Batch> findBatchByServiceProvider(int userId) {
        String sql = "SELECT distinct(b.batch_id),b.custom_label_1_name,b.custom_label_2_name,b.batch_date,b.order_id "
                     + "FROM batch b,order_details o " + "WHERE b.order_id=o.order_id and o.user_id=" + userId;

        return getJdbcTemplate().query(sql, batchMapper);
    }

    @Override
    public Batch findBatchById(int id) {
        String sql = "select * from batch where batch_id=" + id;

        try {
            return (Batch) getJdbcTemplate().queryForObject(sql, batchMapper);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    @Override
    public Batch insertBatch(Batch batch) {
        Map<String, Object> para = new HashMap<String, Object>();

        para.put("custom_label_1_name", (batch.getCustomLabelName1() == null)
                                        ? ""
                                        : batch.getCustomLabelName1());
        para.put("custom_label_2_name", (batch.getCustomLabelName2() == null)
                                        ? ""
                                        : batch.getCustomLabelName2());
        para.put("batch_date", (batch.getBatchDate() == null)
                               ? new Date()
                               : batch.getBatchDate());
        para.put("order_id", batch.getOrderId());

        Number id = jdbcInsert.executeAndReturnKey(para);

        batch.setId(id.intValue());

        return batch;
    }

    @Override
    public void updateBatch(Batch batch) {
        String sql =
            "Update batch set custom_label_1_name=?, custom_label_2_name=?, batch_date=?, order_id=? where batch_id=?";

        getJdbcTemplate().update(sql, new Object[] { batch.getCustomLabelName1(), batch.getCustomLabelName2(),
                batch.getBatchDate(), batch.getOrderId(), batch.getId() });
    }

    @Override
    public void deleteBatch(List<Integer> deletedBatchId) {
        if (deletedBatchId.isEmpty()) {
            return;
        }

        StringBuffer buf    = new StringBuffer("delete from batch where batch_id in (");
        String       concat = "";

        for (Integer id : deletedBatchId) {
            buf.append(concat).append(id);
            concat = ",";
        }

        buf.append(")");
        getJdbcTemplate().execute(buf.toString());
    }

    @Override
    public void deleteBatch(int id) {
        String sql = "delete from batch where batch_id=" + id;

        getJdbcTemplate().execute(sql);
    }

    @Override
    public Page<Batch> find(int pageNumber, int pageSize, String sortColumn, String sortOrder) {
        PaginationHelper<Batch> ph       = new PaginationHelper<Batch>();
        String                  sqlCount = "SELECT count(*) FROM batch";
        String                  sqlQuery = "SELECT * FROM batch order by " + sortColumn + " " + sortOrder;
        Object[]                args     = {};

        return ph.fetchPage(getJdbcTemplate(), sqlCount, sqlQuery, args, pageNumber, pageSize, sortColumn, sortOrder,
                            batchMapper);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Batch> findAll() {
        String      sql    = "SELECT * FROM batch";
        List<Batch> batchs = getJdbcTemplate().query(sql, batchMapper);

        return batchs;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Batch> findToPlaceOrder(List<Integer> batchIds) {
        StringBuffer batchCondition = new StringBuffer();

        if ((batchIds != null) && (batchIds.size() > 0)) {
            batchCondition.append(" and batch_id in (");

            String concat = "";

            for (Integer batchId : batchIds) {
                batchCondition.append(concat).append(batchId);
                concat = ",";
            }

            batchCondition.append(")");
        }

        String      sql    = "SELECT * FROM batch where order_id is null " + batchCondition.toString();
        List<Batch> batchs = getJdbcTemplate().query(sql, batchMapper);

        return batchs;
    }
}



